package edu.sjb_beta1.thread;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import edu.sjb_beta1.gui.GUI;
import edu.sjb_beta1.map.BottomlessPit;
import edu.sjb_beta1.map.LogicMapElement;

public class GravityThread extends Thread {
	public void run() {
		while (true) {
			//Get current coordinates on GUI
			double marioX = GUI.mario.getPositionX();
			double marioY = GUI.mario.getPositionY();
			//Divide by 32 to get block position
			int marioXPos = (int) (marioX / 32);
			int marioYPos = (int) (marioY / 32);
			//Reverse marioYPos to get the grid position and substract 2
			//to locate handling point on lower-left position
			marioYPos = GUI.levelMap.getHeigth() - marioYPos - 2;
			//Get the LogicMapElement of the block inmediately below Mario}
			LogicMapElement belowMario =
				GUI.levelMap.getElementAt(marioXPos, marioYPos).getLogicElement();
			if (belowMario==null //In case Mario is over the air
					|| belowMario.getName().equals(BottomlessPit.ELEMENT_NAME)) { //or over a bottomless pit
				for (int i = 0; i < 2; i++) {
					try {
						GUI.mario.setLocation(
								GUI.mario.getLocation().x,
								GUI.mario.getLocation().y + 16);
						sleep(30);
					}
					catch (Exception e) {
					}
				}
			}
			if (belowMario.getName().equals(BottomlessPit.ELEMENT_NAME)) {
				GUI.mario.goMuerto();
				JOptionPane.showMessageDialog(
						null,
						"Mario has fallen to a bottomless pit! Game is over!",
						"Super JAVA Bros - Game over",
						JOptionPane.INFORMATION_MESSAGE,
						new ImageIcon("./images/character/mario/mariosmall_dead_0.gif")
				);
			}
		}
	}
}